<template>
  <div
    v-loading="isSavePortLoading"
    element-loading-text="处理中..."
    element-loading-spinner="el-icon-loading"
    element-loading-background="rgba(0, 0, 0, 0.8)"
  >
    <div class="tip">
      <span>为保证系统稳定，新添加的帐号，48小时后才可删除；</span>
      <span>如果要修改帐号，请先删除旧帐号再添加新帐号；</span>
    </div>
    <el-form ref="form" :model="bindingAccount" :rules="rules" label-width="100px" size="mini">
      <el-form-item label="城市" prop="city">
        <el-select
          v-model="bindingAccount.city"
          :disabled="handleType === 'edit'"
          filterable
          placeholder="请搜索"
          style="width: 200px"
        >
          <el-option v-for="item in cityOptions" :key="item.code" :label="item.city" :value="item.value"> </el-option>
        </el-select>
      </el-form-item>

      <el-form-item label="账号" prop="account" :error="formError.account">
        <el-input
          v-model="bindingAccount.account"
          placeholder="账号"
          style="width: 200px"
          :disabled="handleType === 'edit'"
          :suffix-icon="handleType === 'edit' ? 'el-icon-lock' : ''"
        ></el-input>
      </el-form-item>

      <el-form-item label="密码" prop="password" :error="formError.password">
        <el-input
          v-model="bindingAccount.password"
          placeholder="密码"
          type="password"
          show-password
          style="width: 200px"
          autocomplete="new-password"
        ></el-input>
      </el-form-item>

      <el-form-item label="图片验证码" prop="verifyCode" :error="formError.verifyCode" v-if="isVerificationCode">
        <div class="d-flex ai-center">
          <el-input
            v-model="bindingAccount.verifyCode"
            placeholder="图片验证码"
            maxlength="4"
            style="width: 100px"
          ></el-input>
          <el-image
            v-loading="isVerifyCodeImgLoading"
            class="ml10"
            style="width: 80px; height: 30px"
            :src="`data:image/png;base64,${bindingAccount.verifyCodeUrl}`"
            fit="fill"
          ></el-image>
          <el-button class="ml10" type="text" :disabled="isVerifyCodeImgLoading" @click="handleRefreshVerifyCode"
            >换一张</el-button
          >
        </div>
      </el-form-item>

      <el-form-item label="短信验证码" prop="telcode" v-if="isVerificationCode">
        <div class="d-flex ai-center">
          <el-input v-model="bindingAccount.telcode" placeholder="短信验证码" style="width: 100px"></el-input>
          <el-button
            class="ml10"
            @click="handleSendMessage"
            :disabled="!bindingAccount.verifyCode || countDownTime !== 60"
            >{{ countDownTime === 60 ? '获取验证码' : `重新获取${countDownTime}s` }}</el-button
          >
        </div>
      </el-form-item>

      <div class="text-red fs-sm text-center" v-if="isVerificationCode && bindingAccount.account">
        {{ bindingAccount.account }}手机号将用于接收验证码，请注意查收
      </div>

      <el-form-item class="d-flex jc-end">
        <el-button type="primary" round @click="handleSubmit">保存</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import CITYS from '@/config/citys';
import { PORT_CODE_AJK, PORT_CODE_XFL_MP } from '@/config/house/platform';
import { debounce } from '@/utils';

export default {
  name: 'PortManagementDialog',

  components: {},

  props: {
    handleType: {
      type: String,
      default: ''
    },
    echoData: {
      type: Object,
      default() {
        return {};
      }
    }
  },

  data() {
    this.cityOptions = CITYS.map((item) => {
      return { ...item, value: item.city };
    });
    this.constant = {
      PORT_CODE_AJK,
      PORT_CODE_XFL_MP,
      ACTION_TYPE_ADD: 'qr_bind',
      ACTION_TYPE_EDIT: 'update'
    };
    this.timer = null; // 计时器
    return {
      isSavePortLoading: false,
      isVerifyCodeImgLoading: false,
      isVerificationCode: false,
      bindingAccount: {
        account: '',
        password: '',
        city: '',
        verifyCode: '',
        telcode: '',
        cookie: '',
        verifyCodeUrl: ''
      },
      formError: {
        account: '',
        password: '',
        verifyCode: ''
      }, // 异步错误
      countDownTime: 60, // 验证码时间
      rules: {
        account: [{ required: true, message: '账号不能为空', trigger: 'blur' }],
        password: [
          { required: true, message: '密码不能为空', trigger: 'blur' },
          { min: 6, message: '密码不能少于6位', trigger: 'blur' }
        ],
        city: [{ required: true, message: '城市不能为空', trigger: 'change' }],
        verifyCode: [{ required: true, message: '图片验证不能为空', trigger: 'blur' }],
        telcode: [{ required: true, message: '短信验证不能为空', trigger: 'blur' }]
      }
    };
  },

  computed: {},

  watch: {
    echoData: {
      handler: function(val) {
        const { handleType } = this;
        if (!val || handleType !== 'edit') return;
        const { account, portUserCity, accountVerifyVo = {} } = val;
        Object.assign(this.bindingAccount, {
          account: account || '',
          city: portUserCity || '',
          cookie: accountVerifyVo.cookie || '',
          verifyCodeUrl: accountVerifyVo.verifyPngData || ''
        });
        this.loadPortPassword();
        if (accountVerifyVo.cookie && accountVerifyVo.verifyPngData) {
          this.isVerificationCode = true;
        }
      },
      immediate: true
    }
  },

  created() {
    // 点击保存
    this.handleSubmit = debounce(
      () => {
        this.submit('form');
      },
      400,
      false
    );
  },

  beforeMount() {},

  mounted() {},

  methods: {
    // ------------------handle------------------
    // 点击刷新图片验证码
    handleRefreshVerifyCode() {
      this.loadVerifyCode();
    },
    // 点击发送短信
    handleSendMessage() {
      this.sendMessage();
    },
    // ------------------function------------------
    // 提交表单
    submit(formName) {
      this.$refs[formName].validate((valid) => {
        if (!valid) return false;
        const { handleType } = this;
        switch (handleType) {
          case 'add':
            this.addAccount();
            break;
          case 'edit':
            this.editAccount();
            break;
        }
      });
    },
    // 添加端口
    async addAccount() {
      try {
        this.isSavePortLoading = true;
        const { account, password, city, cookie, telcode, verifyCode } = this.bindingAccount;
        const { portType } = this.echoData;
        const res = await this.$api.addAccount({
          portType,
          account,
          password,
          city,
          cookie,
          telcode,
          verifyCode
        });
        const result = res.content || {};
        gio('track', 'bindPortResult', {
          handle_type: 'add',
          port_channel: portType,
          result_code: result.statusCode,
          result_msg: result.reason
        });
        if (res && res.isSuccess && res.content.status === '1') {
          this.$message.success('绑定成功!');
          this.$emit('portChange');
          this.$emit('close');
        } else {
          this.solvePortError({
            errorCode: result.statusCode,
            errorMessage: result.reason || '绑定失败，请稍后再试~',
            errorParams: result.accountVerifyVo || {}
          });
        }
      } catch (error) {
        console.log('error: ' + error);
      } finally {
        this.isSavePortLoading = false;
      }
    },

    // 更新端口
    async editAccount() {
      try {
        this.isSavePortLoading = true;
        const { isVerificationCode } = this;
        const { account, password, city, cookie, telcode, verifyCode } = this.bindingAccount;
        const { id, portType } = this.echoData;
        const res = await this.$api.updateAccount({
          id,
          portType,
          account,
          password,
          city,
          cookie,
          telcode,
          verifyCode
        });
        const result = res.content || {};
        gio('track', 'bindPortResult', {
          port_id: id,
          port_channel: portType,
          handle_type: 'edit',
          result_code: result.statusCode,
          result_msg: result.reason
        });
        if (res && res.isSuccess && res.content.status === '1') {
          this.$message.success('修改成功!');
          this.$emit('portChange');
          this.$emit('close');
        } else {
          this.solvePortError({
            errorCode: result.statusCode,
            errorMessage: result.reason || (isVerificationCode ? '保存失败，请稍后再试~' : '修改失败，请稍后再试~'),
            errorParams: result.accountVerifyVo || {}
          });
        }
      } catch (error) {
        console.log('error: ' + error);
      } finally {
        this.isSavePortLoading = false;
      }
    },

    // 处理端口错误
    solvePortError({ errorCode, errorMessage, errorParams = {} }) {
      // 端口需要扫码登录
      if (['account_login.port_qr_code'].indexOf(errorCode) !== -1) {
        this.$message({ type: 'error', message: errorMessage || '操作失败，请稍后再试~', customClass: 'top-index' });
        this.solveErrorScan();
        return;
      }
      // 端口需要验证码校验
      if (['account_login.check_mobile'].indexOf(errorCode) !== -1) {
        this.$message.error(errorMessage || '操作失败，请稍后再试~');
        this.solveErrorVerificationCode(errorParams);
        return;
      }
      // 账号错误
      if (
        [
          'account_login.account_exist',
          'account_login.port_exist',
          'account_login.account_time_bind',
          'account_login.name_or_pass_fail'
        ].indexOf(errorCode) !== -1
      ) {
        this.solveErrorAccount(errorMessage);
        return;
      }
      // 密码错误
      if (['account_login.account_password_no_change', 'account_login.name_or_pass_fail'].indexOf(errorCode) !== -1) {
        this.solveErrorPassword(errorMessage);
        return;
      }
      // 默认处理
      this.$message.error(errorMessage || '操作失败，请稍后再试~');
    },

    // 处理端口需要扫码
    solveErrorScan() {
      const { account, city } = this.bindingAccount;
      const { portType } = this.echoData;
      this.$emit('close', {
        code: 'LOGIN_SCAN',
        msg: '账号需要扫码登录',
        data: {
          portType,
          account,
          city,
          action: this.constant[`ACTION_TYPE_${this.handleType.toUpperCase()}`]
        }
      });
    },

    // 处理端口错误验证码
    solveErrorVerificationCode(errorParams) {
      this.isVerificationCode = true;
      this.bindingAccount.cookie = errorParams.cookie || '';
      this.bindingAccount.verifyCodeUrl = errorParams.verifyPngData || '';
    },

    // 处理端口错误账号
    solveErrorAccount(errorMessage) {
      this.formError.account = '';
      this.$nextTick(() => {
        this.formError.account = errorMessage;
      });
    },

    // 处理端口错误密码
    solveErrorPassword(errorMessage) {
      this.formError.password = '';
      this.$nextTick(() => {
        this.formError.password = errorMessage;
      });
    },

    // 加载图片验证码
    async loadVerifyCode() {
      try {
        this.isVerifyCodeImgLoading = true;
        const { account, city } = this.bindingAccount;
        const { portType } = this.echoData;
        const res = await this.$api.getVerificationCode({
          account,
          portType,
          city
        });
        if (res && res.content && res.content.verifyPngData) {
          this.bindingAccount.cookie = res.content.cookie || '';
          this.bindingAccount.verifyCodeUrl = res.content.verifyPngData || '';
        }
      } catch (error) {
        console.log('error: ' + error);
      } finally {
        this.isVerifyCodeImgLoading = false;
      }
    },

    // 发送短信
    async sendMessage() {
      try {
        this.startCountDown(this.countDownTime);
        const { account, city, verifyCode, cookie } = this.bindingAccount;
        const { portType } = this.echoData;
        const res = await this.$api.sendVerification({
          account,
          portType,
          city,
          cookie,
          verifyCode
        });
        if (res && res.content && res.content.status === 'success') {
        } else {
          this.formError.verifyCode = '';
          this.$nextTick(() => {
            this.formError.verifyCode = res.content.msg || '';
          });
          this.bindingAccount.verifyCode = '';
          this.loadVerifyCode();
          this.resetCountDown();
        }
      } catch (error) {
        console.log('error: ' + error);
      }
    },

    // 倒计时器
    startCountDown(time = 60) {
      if (this.countDownTime < time) return;
      this.countDownTime--;
      this.timer = setInterval(() => {
        this.countDownTime--;
        if (this.countDownTime < 0) {
          clearInterval(this.timer);
          this.countDownTime = time;
        }
      }, 1000);
    },

    // 重置倒计时
    resetCountDown() {
      this.countDownTime = 60;
      clearInterval(this.timer);
      this.timer = null;
    },

    // 加载端口密码
    async loadPortPassword() {
      try {
        const { id } = this.echoData;
        const res = await this.$api.getPortPassword({ id });
        if (res && res.content) {
          this.bindingAccount.password = res.content;
        }
      } catch (error) {
        console.log('error' + error);
      }
    }
  }
};
</script>

<style lang="scss" scoped>
.tip {
  display: flex;
  flex-direction: column;
  margin-top: -10px;
  margin-bottom: 20px;
  padding: 10px 24px;
  font-size: 10px;
  line-height: 2;
  color: #ee4d4d;
  font-weight: 700;
  background: #fff4f4;
}
</style>

<style>
.top-index {
  z-index: 3000 !important;
}
</style>
